﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using DIWAGIS;
using DIWAGIS.ApplicationLayer.XemThongTin;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Display;

namespace DIWAGIS.ApplicationLayer.BoCongCuQuanLy
{
    /// <summary>
    /// Summary description for ToolUpdateCoordinate.
    /// </summary>
    [Guid("26767a08-08a1-4cf3-a5e0-f8996f6a15dd")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("DIWAGIS.ApplicationLayer.BoCongCuQuanLy.ToolUpdateCoordinate")]
    public sealed class ToolUpdateCoordinate : BaseTool
    {
        #region COM Registration Function(s)
        [ComRegisterFunction()]
        [ComVisible(false)]
        static void RegisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryRegistration(registerType);

            //
            // TODO: Add any COM registration code here
            //
        }

        [ComUnregisterFunction()]
        [ComVisible(false)]
        static void UnregisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryUnregistration(registerType);

            //
            // TODO: Add any COM unregistration code here
            //
        }

        #region ArcGIS Component Category Registrar generated code
        /// <summary>
        /// Required method for ArcGIS Component Category registration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryRegistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            MxCommands.Register(regKey);
            ControlsCommands.Register(regKey);
        }
        /// <summary>
        /// Required method for ArcGIS Component Category unregistration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryUnregistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            MxCommands.Unregister(regKey);
            ControlsCommands.Unregister(regKey);
        }

        #endregion
        #endregion

        private frmCapNhatThongTinToaDo m_frmCapNhatToaDo;
        public frmCapNhatThongTinToaDo frmCapNhatToaDo
        {
            get { return m_frmCapNhatToaDo; }
            set { m_frmCapNhatToaDo = value; }
        }
        private IHookHelper m_hookHelper = null;
        private IMapControl4 m_map;
        private ILayer m_targetLayer;
        public ILayer targetLayer
        {
            get { return m_targetLayer; }
            set { m_targetLayer = value; }
        }

        private IEngineEditor m_editor;
        public IEngineEditor editor
        {
            get { return m_editor; }
            set { m_editor = value; }
        }

        public ToolUpdateCoordinate()
        {
            //
            // TODO: Define values for the public properties
            //
            base.m_category = "Cập nhật tọa độ"; //localizable text 
            base.m_caption = "Cập nhật tọa độ";  //localizable text 
            base.m_message = "Cập nhật tọa độ";  //localizable text
            base.m_toolTip = "Cập nhật tọa độ";  //localizable text
            base.m_name = "Cập nhật tọa độ";   //unique id, non-localizable (e.g. "MyCategory_MyTool")
            try
            {
                //
                // TODO: change resource name if necessary
                //
                string bitmapResourceName = GetType().Name + ".bmp";
                base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
                base.m_cursor = new System.Windows.Forms.Cursor(GetType(), GetType().Name + ".cur");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
            }
        }

        #region Overridden Class Methods

        /// <summary>
        /// Occurs when this tool is created
        /// </summary>
        /// <param name="hook">Instance of the application</param>
        public override void OnCreate(object hook)
        {
            try
            {
                m_hookHelper = new HookHelperClass();
                m_hookHelper.Hook = hook;
                if (m_hookHelper.ActiveView == null)
                {
                    m_hookHelper = null;
                }
            }
            catch
            {
                m_hookHelper = null;
            }

            if (m_hookHelper == null)
                base.m_enabled = false;
            else
                base.m_enabled = true;

            // TODO:  Add other initialization code
            if (m_hookHelper.Hook is IMapControl4)
            {
                m_map = (IMapControl4)m_hookHelper.Hook;
            }
            else if (m_hookHelper.Hook is IToolbarControl2)
            {
                IToolbarControl2 _toolBar;
                _toolBar = (IToolbarControl2)m_hookHelper.Hook;
                m_map = (IMapControl4)_toolBar.Buddy;
            }
        }

        /// <summary>
        /// Occurs when this tool is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add ToolUpdateCoordinate.OnClick implementation
            foreach (var item in Application.OpenForms)
            {
                if (item is frmCapNhatThongTinToaDo)
                {
                    m_frmCapNhatToaDo = ((frmCapNhatThongTinToaDo)item);
                    m_frmCapNhatToaDo.Activate();
                }
            }
        }

        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolUpdateCoordinate.OnMouseDown implementation
            IFeature featureSelected = null;
            IMap pMap;
            IFeatureLayer crLayer;
            ISpatialFilter iFilter = new SpatialFilter();
            m_map.Map.ClearSelection();
            pMap = m_map.ActiveView.FocusMap; //Gets the Map
            crLayer = m_targetLayer as IFeatureLayer;
            if (crLayer == null)
                return;
            //pEnumFeature = pMap.FeatureSelection as IEnumFeature;

            IPoint clickedPoint = m_map.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            IActiveView activeView = m_map.ActiveView;
            IRubberBand rubberEnv = new RubberEnvelopeClass();
            IGeometry geom = rubberEnv.TrackNew(activeView.ScreenDisplay, null);
            IArea area = (IArea)geom;

            if ((geom.IsEmpty == true) || (area.Area == 0))
            {
                IEnvelope tempEnv = new EnvelopeClass();
                ESRI.ArcGIS.esriSystem.tagRECT RECT = new ESRI.ArcGIS.esriSystem.tagRECT();
                RECT.bottom = 0;
                RECT.left = 0;
                RECT.right = 5;
                RECT.top = 5;
                //transform rectangle into map units and apply to the tempEnv envelope 
                IDisplayTransformation dispTrans = activeView.ScreenDisplay.DisplayTransformation;
                dispTrans.TransformRect(tempEnv, ref RECT, 4); //4 = esriDisplayTransformationEnum.esriTransformToMap)
                tempEnv.CenterAt(clickedPoint);
                geom = (IGeometry)tempEnv;
            }

            //Set the spatial reference of the search geometry to that of the Map 
            ISpatialReference spatialReference = m_map.SpatialReference;
            geom.SpatialReference = spatialReference;
            iFilter.Geometry = geom;
            iFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            IFeatureCursor cur = crLayer.Search(iFilter, false);//crLayer.Search(iFilter, true);
            featureSelected = cur.NextFeature();
            m_map.Map.SelectFeature(crLayer, featureSelected);
            m_map.ActiveView.Refresh();
            if (m_editor.EditState != esriEngineEditState.esriEngineStateEditing)
            {
                Class.clsStaticFunctions.CanhBao("Bạn phải bật chế độ chỉnh sửa để cập nhật tọa độ đối tượng!");
                return;
            }
            if (featureSelected != null)
               m_frmCapNhatToaDo.SelectedFeature = featureSelected;
            else
                m_frmCapNhatToaDo.ClearData();
        }

        public override void OnMouseMove(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolUpdateCoordinate.OnMouseMove implementation
        }

        public override void OnMouseUp(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolUpdateCoordinate.OnMouseUp implementation
        }
        #endregion
    }
}
